package com.dream.libxrec.sound;

import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class XAudioRecord extends ISoundRec {

    private final int BUFFER_SIZE = 2048;
    private final byte[] mBuffer = new byte[BUFFER_SIZE];
    private volatile boolean mIsRec = false;//是否正在录音
    private AudioRecord mAudioRecord = null;//录音器
    private final ExecutorService mThreadPool = Executors.newSingleThreadExecutor();

    /**
     *
     * @param sampleRate 采样率：44100
     * @param channelNum 通道数，1或2
     * @param quantBits 量化位数 8、16、24、32等
     * @param extra 为空即可
     */
    @SuppressLint("MissingPermission")
    @Override
    public ISoundRec init(Context ct, int sampleRate,
                     int channelNum, int quantBits
            , Bundle extra) {

        int audioSource = MediaRecorder.AudioSource.MIC;

        //单声道输入
        int channelConfig =
                channelNum == 1?AudioFormat.CHANNEL_IN_MONO:
                        AudioFormat.CHANNEL_IN_STEREO;

        int audioFormat;
        switch (quantBits){
            case 8:
                audioFormat = AudioFormat.ENCODING_PCM_8BIT;
                break;
            case 24:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    audioFormat = AudioFormat.ENCODING_PCM_24BIT_PACKED;
                    break;
                }
            case 32:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    audioFormat = AudioFormat.ENCODING_PCM_32BIT;
                    break;
                }
            default:
                //PCM16是所有安卓系统都支持的格式
                audioFormat = AudioFormat.ENCODING_PCM_16BIT;
                break;
        }


        //计算AudioRecord内部buffer的最小的大小
        int minBufferSize = AudioRecord.getMinBufferSize(sampleRate
                ,channelConfig,audioFormat);

        //最后一个参数，bufferSize不能小于最低要求，也不能小于我们读取的大小
        mAudioRecord = new AudioRecord(audioSource,sampleRate,channelConfig
                ,audioFormat,Math.max(minBufferSize,BUFFER_SIZE));

        return this;
    }

    @Override
    public boolean isRun() {
        return mIsRec;
    }

    public void start(){
        mThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                mIsRec = true;
                mAudioRecord.startRecording();//开始录音

                while (mIsRec){
                    int size = mAudioRecord.read(mBuffer,0,
                            BUFFER_SIZE);
                    if (size > 0){
                        if (mSoundRecListener != null){
                            mSoundRecListener.onSoundRec(mBuffer,size);
                        }
                    }
                }

                mIsRec = false;
                mAudioRecord.stop();
                mAudioRecord.release();
            }
        });
    }

    public void stop(){
        mIsRec = false;
    }
}
